package com.mingserve.common.mqtt.utils;

import io.micrometer.common.util.StringUtils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

/**
 * Net工具类
 *
 * @author lvwshuai
 * @date 2024-02-22
 */
public class NetUtils
{
    /**
     * 获取Mac地址
     * ENTRYPOINT MAC_ADDRESS=$(cat /host_sys/class/net/eth0/address) && \
     *            java -Djava.security.egd=file:/dev/./urandom -Dserver.port=${SERVER_PORT} \
     *            -Dmac.address=${MAC_ADDRESS} -jar jar/msw-admin.jar ${JAVA_OPTS}
     * @return 返回-D启动参数mac.address 未设置则返回本容器Mac
     */
    public static String getMacAddress()
    {
        String macAddress = System.getProperty("mac.address");
        return StringUtils.isNotEmpty(macAddress) ? macAddress.replace(":", "") : getLocalMacAddress().replace("-", "");
    }

    /**
     * 获取Mac地址（取第一个有IP的）
     *
     * @return
     */
    public static String getLocalMacAddress()
    {
        try {
            // 遍历所有的网络接口
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface networkInterface = interfaces.nextElement();
                // 在所有的接口下再遍历IP
                Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
                while (addresses.hasMoreElements()){
                    InetAddress address = addresses.nextElement();
                    //排除LoopbackAddress、SiteLocalAddress、LinkLocalAddress、MulticastAddress类型的IP地址
                    if (!address.isLoopbackAddress() /*&& !inetAddr.isSiteLocalAddress()*/
                            && !address.isLinkLocalAddress()
                            && !address.isMulticastAddress()) {
                        byte[] mac = networkInterface.getHardwareAddress();
                        if (mac != null) {
                            StringBuilder sb = new StringBuilder();
                            for (int i = 0; i < mac.length; i++) {
                                // %02x：x 表示以十六进制小写形式输出，02 意味着输出的十六进制数宽度为 2 位，若不足 2 位则在前面补 0
                                sb.append(String.format("%02x%s", mac[i], (i < mac.length - 1) ? "-" : ""));
                            }
                            return sb.toString();
                        }
                    }
                }
            }
        } catch (Exception ignored) { }
        return "";
    }
}